<?php

class Ext_Controller_Action_Admin extends Ext_Controller_Action
{
    public function init(){
        parent::init();
        
        Zend_Registry::set('_use_adapter', 'master');
    }
    
    public function preDispatch()
    {
        parent::preDispatch();
        
        $moduleName     = $this->_request->getModuleName();
        $controllerName = $this->_request->getControllerName();
        $actionName     = $this->_request->getActionName();
        
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        if($userId < 1){
            $this->_forward("show-please-login", "auth", "account");
        }

        if($controllerName == 'auth'){
            return "";
        }
        
        $user = Ext_User::getInstance()->show($userId)->buildRole();
        if($user->role->roleType != 'admin'){
            $this->_forward("show-access-denied", "auth", "account");
        }

        $userId = Ext_Auth_Admin::getInstance()->getIdentity();
        if($userId < 1){
            $this->_forward("show-login-form", "auth", "admin");
        }
        
        if($controllerName != 'auth'){
            $_array = explode("-", $controllerName);
            $_controllerFirstName = $_array['0'];
            if(isset($_array['1'])){
                $_controllerSecondName = $_array['1'];
            }
            $_renderFileName = "module_admin_script_menu-left-".$_controllerFirstName.".phtml";
            $response = Zend_Controller_Front::getInstance()->getResponse();

            $response->insert('menuLeftList', $this->view->render($_renderFileName));

            $this->view->controllerFirstName = $_controllerFirstName;
            if(isset($_controllerSecondName)){
                $this->view->controllerSecondName = $_controllerSecondName;
            }
        }
        
        if($userId > 1){
            $roleId = $user->roleId;
            if(!$roleId){
                $this->_forward("show-access-denied", "auth", "account");
            }
            $acl = Ext_Acl::getInstance()->build($roleId);
            if(!$acl->has($moduleName)){
                $acl->add(new Zend_Acl_Resource($moduleName));
            }
            if(!$acl->isAllowed($roleId, $moduleName, $controllerName)){
                $this->_forward("show-access-denied", "auth", "admin");
            }
        }
    }
}
